package cn.fl.flow.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.flow.condition.SysFlowRejRsnQueryCondition;
import cmm.mid.core.framework.constant.CacheRefreshConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.comm.service.ICacheRefreshService;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.flow.service.IFlowService;
import cn.fl.flow.service.ISysFlowRejRsnService;
import cn.fl.flow.vo.SysFlowRejRsnVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.constant.SysTipConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 流程驳回原因表 控制层
 */
@Controller
@RequestMapping("/flow/sysflowrejrsn")
public class SysFlowRejRsnController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysFlowRejRsnController.class);

	/**
	 * SysFlowRejRsn 服务层BEAN
	 */
	@Autowired
	private ISysFlowRejRsnService sysFlowRejRsnService;
	
	/**
	 * 本地缓存刷新服务
	 */
	@Autowired
	private ICacheRefreshService cacheRefreshService;
	
	/**
	 * 任务服务
	 */
	@Autowired
	private IFlowService flowService;
	
	@Autowired
    private ICstBscInfoService cstBscInfoService;
	
	
	/**
	 * 初始化列表点一次查一次
	 * /flow/sysflowrejrsn/initTreeList.do
	 */
	@RequestMapping(value = "/initTreeList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initTreeList(HttpServletRequest request, HttpServletResponse response) {
		String rsnTypCd = request.getParameter("rsnTypCd");
		String buOrgCd = request.getParameter("buOrgCd");
		String id = request.getParameter("id");
		try {
			//JSONArray jsonArray = this.sysOrgService.searchList(SysOrgConstant.SYS_ORG_CD_PID_INIT);
			//JSONArray jsonArray = this.sysFlowRejRsnService.searchRejRsnTreeByCon(rsnTypCd, buOrgCd,CurrentThreadContext.getCurrentSysCd());
			JSONArray jsonArray = this.sysFlowRejRsnService.searchRejRsnTreeByCon(Long.valueOf(id),rsnTypCd, buOrgCd,CurrentThreadContext.getCurrentSysCd());
			BaseLogUtils.info(logger, "initList", "初始化组织架构列表页面.",CurrentThreadContext.getCurrentUserName());
			return jsonArray;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "初始化组织架构列表页面失败.系统错误:"+e.getMessage(),CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载信审意见列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysRejRsn/sysRejRsnlist");
		List<KeyValueVO> rejRsnList = this.flowService.searchRejRsnList();
		view.addObject("rejRsnList", rejRsnList);
		//事业部
		List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
		view.addObject("buOrgCdList", orgList);
		return view;
	}

	/**
	 * 到修改页面
	 * 	/flow/sysflowrejrsn/toModifyPage.do
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("flow/sysFlowRejRsn/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 * flow/sysflowrejrsn/initList.do
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		//String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysFlowRejRsnQueryCondition qc = new SysFlowRejRsnQueryCondition();
		page.setCondition(qc);

		Pager pager = new Pager();//this.sysFlowRejRsnService.searchListPage(page);
		List<SysFlowRejRsnVO> list = (List<SysFlowRejRsnVO>) pager.getResultList();
		ListPageVO<SysFlowRejRsnVO> listPage = new ListPageVO<SysFlowRejRsnVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String rsnTypCd = request.getParameter("rsnTypCd");
		String orgCd = request.getParameter("orgCd");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.sysFlowRejRsnService.removeById(Long.valueOf(id),rsnTypCd,orgCd);
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysFlowRejRsnVO vo = this.sysFlowRejRsnService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysFlowRejRsnVO entity = null;
		try {
			entity =  this.getRequestParamForSysFlowRejRsn(request);
			Long id = this.sysFlowRejRsnService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	private  SysFlowRejRsnVO getRequestParamForSysFlowRejRsn(HttpServletRequest request)throws BaseException{
		String pid = request.getParameter("pid");
		SysFlowRejRsnVO sysFlowRejRsnVO = this.getRequestParamForSysFlowRejRsnVO(request);
		if(StringUtils.isNotBlank(pid)){
			sysFlowRejRsnVO.setPid(Long.valueOf(pid));
		}
		if(StringUtils.isNotBlank(pid)&&pid.equals("0")){
			sysFlowRejRsnVO.setRsnLvl(1);
		}else{
			SysFlowRejRsnVO sysFlowRejRsn = this.sysFlowRejRsnService.selectById(Long.valueOf(pid));
			sysFlowRejRsnVO.setRsnLvl(sysFlowRejRsn.getRsnLvl()+1);
		}
		
		sysFlowRejRsnVO.setCrtTm(new Date());
		sysFlowRejRsnVO.setIsDel(BaseConstant.IS_YESNO_NO);
		sysFlowRejRsnVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		sysFlowRejRsnVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		return sysFlowRejRsnVO;
	}
	
	private SysFlowRejRsnVO getRequestParamForSysFlowRejRsnVO(HttpServletRequest request)throws BaseException{
		
		String  rsnTypCd = request.getParameter("rsnTypCd");//原因分类
		String  orgCd = request.getParameter("orgCd");//组织机构代码
		String  sortNo = request.getParameter("sortNo");//排序
		String  rsnDesc = request.getParameter("rsnDesc");//原因描述
		
		//验证 必填项 以及长度
		if(StringUtils.isBlank(rsnTypCd) ){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "原因分类不能为空");
		}
		if(StringUtils.isBlank(orgCd) ){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "组织机构代码不能为空");
		}
		SysFlowRejRsnVO sysFlowRejRsnVO = new SysFlowRejRsnVO();
		sysFlowRejRsnVO.setRsnTypCd(rsnTypCd);
		sysFlowRejRsnVO.setOrgCd(orgCd);
		if(StringUtils.isNotBlank(sortNo) && StringUtils.isNumeric(sortNo)){
			sysFlowRejRsnVO.setSortNo(Long.valueOf(sortNo));
		}else{
			sysFlowRejRsnVO.setSortNo(0L);
		}
		if(StringUtils.isNotBlank(rsnDesc)){
			sysFlowRejRsnVO.setRsnDesc(rsnDesc);
		}
		return sysFlowRejRsnVO;
		
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		//String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysFlowRejRsnVO entity = null;
		try {
			entity = this.sysFlowRejRsnService.selectById(Long.valueOf(id));
			SysFlowRejRsnVO entityNew = this.getRequestParamForSysFlowRejRsnVO(request);
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setRsnTypCd(entityNew.getRsnTypCd());
			entity.setRsnDesc(entityNew.getRsnDesc());
			entity.setOrgCd(entityNew.getOrgCd());
			entity.setSortNo(entityNew.getSortNo());
			//entity.setName(name);
			boolean success = this.sysFlowRejRsnService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

}

